package com.mikufufu.blog.storage.enums;

import com.mikufufu.blog.storage.mode.LocalMode;
import com.mikufufu.blog.storage.mode.MinioMode;
import com.mikufufu.blog.storage.mode.OssMode;
import com.mikufufu.blog.storage.StorageMode;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import com.mikufufu.blog.utils.StringUtils;

import javax.validation.constraints.NotNull;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 存储类型枚举类
 * 
 */
@Slf4j
@Getter
@AllArgsConstructor
public enum StorageType {

    local(0,"local", LocalMode.class),
    minio(1,"minio", MinioMode.class),
    aliyun(2,"oss", OssMode.class),
    ;

    private final Integer type;

    private final String code;

    /**
     * 存储模式的类
     */
    private final Class<? extends StorageMode> storageMode;

    /**
     *
     * @param type 存储方式的类型
     * @return {@link StorageType} 存储方式枚举类
     */
    public static StorageType getStorageType(@NotNull Integer type){
        for (StorageType storageType : StorageType.values()){
            if (type.equals(storageType.getType())){
                return storageType;
            }
        }
        return null;
    }

    /**
     * 获取存储模式
     * @param code 存储方式的code
     * @return {@link StorageMode} 存储模式
     */
    public static StorageMode getStorageMode(String code){
        if(StringUtils.isBlank(code)){
            throw new RuntimeException("存储方式不能为空");
        }
        try {
            // 遍历枚举类
            for (StorageType storageType : StorageType.values()) {
                if (storageType.getCode().equals(code)){
//                    return storageType.getStorageMode().newInstance();
                    // 17 版本以上废弃了 newInstance 方法，可以改用Constructor 的 newInstance 方法来创建对象
                    Constructor<? extends StorageMode> constructor = storageType.getStorageMode().getDeclaredConstructor();
                    return constructor.newInstance();
                }
            }
        } catch (InvocationTargetException | NoSuchMethodException | InstantiationException | IllegalAccessException e) {
            log.error("获取存储方式失败：{}",e.getMessage());
        }
        throw new RuntimeException("获取存储方式失败");
    }

}
